<template>
  <div class="profile-settings">
    <a-card :bordered="false">
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" :tab="t('profile.settings.basic')">
          <a-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item :label="t('profile.settings.avatar')">
              <a-upload
                v-model:file-list="fileList"
                name="avatar"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                @change="handleAvatarChange"
              >
                <div v-if="basicForm.avatar">
                  <img :src="basicForm.avatar" alt="avatar" class="avatar" />
                </div>
                <div v-else>
                  <plus-outlined />
                  <div style="margin-top: 8px">{{ t('profile.settings.upload') }}</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item name="nickname" :label="t('profile.nickname')">
              <a-input v-model:value="basicForm.nickname" />
            </a-form-item>
            <a-form-item name="phone" :label="t('profile.phone')">
              <a-input v-model:value="basicForm.phone" />
            </a-form-item>
            <a-form-item name="email" :label="t('profile.email')">
              <a-input v-model:value="basicForm.email" />
            </a-form-item>
            <a-form-item name="bio" :label="t('profile.settings.bio')">
              <a-textarea v-model:value="basicForm.bio" :rows="4" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" @click="saveBasicSettings" :loading="basicSaving">
                {{ t('common.save') }}
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        
        <a-tab-pane key="2" :tab="t('profile.settings.preferences')">
          <a-form
            :model="preferencesForm"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item :label="t('profile.settings.language')">
              <a-select v-model:value="preferencesForm.language">
                <a-select-option value="zh-CN">简体中文</a-select-option>
                <a-select-option value="en-US">English</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item :label="t('profile.settings.theme')">
              <a-radio-group v-model:value="preferencesForm.theme">
                <a-radio value="light">{{ t('profile.settings.light') }}</a-radio>
                <a-radio value="dark">{{ t('profile.settings.dark') }}</a-radio>
                <a-radio value="system">{{ t('profile.settings.system') }}</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item :label="t('profile.settings.notifications')">
              <a-checkbox-group v-model:value="preferencesForm.notifications">
                <a-row>
                  <a-col :span="24">
                    <a-checkbox value="email">{{ t('profile.settings.emailNotifications') }}</a-checkbox>
                  </a-col>
                  <a-col :span="24">
                    <a-checkbox value="system">{{ t('profile.settings.systemNotifications') }}</a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" @click="savePreferencesSettings" :loading="preferencesSaving">
                {{ t('common.save') }}
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, UploadChangeParam, UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { uploadAvatar } from '@/api/auth'

// 定义组件名
defineOptions({
  name: 'ProfileSettings'
})

// 国际化
const { t } = useI18n()

// 获取用户store
const authStore = useAuthStore()
const userInfo = authStore.userInfo || {
  avatar: '',
  nickname: '',
  email: '',
  phone: '',
  bio: ''
}

// 基本信息表单
const basicFormRef = ref<FormInstance>()
const basicForm = reactive({
  avatar: userInfo.avatar || '',
  nickname: userInfo.nickname || '',
  email: userInfo.email || '',
  phone: userInfo.phone || '',
  bio: ''
})

// 表单验证规则
const basicRules = {
  nickname: [
    { required: true, message: t('profile.settings.nicknameRequired'), trigger: 'blur' },
    { min: 2, max: 20, message: t('profile.settings.nicknameLength'), trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: t('profile.settings.emailInvalid'), trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: t('profile.settings.phoneInvalid'), trigger: 'blur' }
  ]
}

// 偏好设置表单
const preferencesForm = reactive({
  language: 'zh-CN',
  theme: 'light',
  notifications: ['email', 'system']
})

// 头像上传相关
const fileList = ref([])
const basicSaving = ref(false)
const preferencesSaving = ref(false)

// 头像上传前检查
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error(t('profile.settings.avatarTypeError'))
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error(t('profile.settings.avatarSizeError'))
    return false
  }
  
  return false // 阻止自动上传，改为手动上传
}

// 头像变更处理
const handleAvatarChange = async (info: UploadChangeParam) => {
  const file = info.file.originFileObj
  if (!file) return
  
  basicSaving.value = true
  try {
    // 调用上传头像API
    const res = await uploadAvatar(file)
    if (res.success && res.data.avatar) {
      // 更新头像URL
      basicForm.avatar = res.data.avatar
      // 更新用户信息
      await authStore.fetchUserInfo()
      message.success(t('profile.settings.avatarUploadSuccess'))
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    message.error(t('profile.settings.avatarUploadFailed'))
  } finally {
    basicSaving.value = false
  }
}

// 保存基本设置
const saveBasicSettings = () => {
  basicFormRef.value?.validate().then(async () => {
    basicSaving.value = true
    try {
      // TODO: 调用保存用户信息API
      // await api.updateUserInfo(basicForm)
      
      setTimeout(() => {
        // 展示成功信息
        message.success(t('profile.settings.saveSuccess'))
        basicSaving.value = false
        
        // 注意：这里只是模拟更新，实际应用中应通过API更新
        // 实际项目中，建议通过统一的API和Store方法来更新用户信息
      }, 1000)
    } catch (error) {
      console.error('Save basic settings failed:', error)
      basicSaving.value = false
    }
  })
}

// 保存偏好设置
const savePreferencesSettings = () => {
  preferencesSaving.value = true
  
  try {
    // TODO: 调用保存偏好设置API
    // await api.updateUserPreferences(preferencesForm)
    
    setTimeout(() => {
      message.success(t('profile.settings.saveSuccess'))
      preferencesSaving.value = false
    }, 1000)
  } catch (error) {
    console.error('Save preferences failed:', error)
    preferencesSaving.value = false
  }
}

// 初始化
onMounted(() => {
  // 加载用户偏好设置
  // TODO: 调用获取用户偏好设置API
})
</script>

<style lang="scss" scoped>
.profile-settings {
  .avatar-uploader {
    text-align: center;
    
    .avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
    }
  }
}
</style> 